import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  let TutorialManager = require("../../Tutorials/TutorialManager");

  const GAME_BANNER_ID = [

  ];


  const MAX_BANNER_LOAD_COUNT = 2;
  let _loadedBanners = [];  //已经加载的banner
  let _currentBanner = null;  //当前正在显示的banner
  let _bannerStyleStack = [];  //banner样式堆栈, 用来维护多次显示banner时的样式
  let _lastBannerOpts;

  let initGameBanner = function () {
    console.log("initGameBanner");
    for (let i = 0; i < GAME_BANNER_ID.length; i++) {
      if (i >= MAX_BANNER_LOAD_COUNT)  //不载入过多的banner,避免影响性能
        break;
      let bannerId = GAME_BANNER_ID[i];
      _createGameBanner(bannerId, true);
    }
  };

  let _createGameBanner = function (bannerId, isPreload) {
    if (wx.createGameBanner === undefined) {
      console.log("banner推荐位初始化失败,微信版本太低");
      return null;
    }
    if (isPreload && _loadedBanners.length >= MAX_BANNER_LOAD_COUNT) {
      console.log('已载入Banner数量已达上限');
      return null;
    }

    let sysInfo = wx.getSystemInfoSync();
    let {screenHeight} = sysInfo;

    let banner = wx.createGameBanner({
      adUnitId: bannerId,
      style: {
        top: screenHeight + 200,
        left: 0,
      }
    });
    banner.bannerId = bannerId;
    banner.useTimes = 0;
    banner.onResize(() => {
      let style = banner.resizeToStyle;
      if (!style) {
        console.warn("Banner.onResize失败, 无resizeToStyle");
        return;
      }
      let sysInfo = wx.getSystemInfoSync();
      let {screenWidth, screenHeight} = sysInfo;

      if (style.posType === 'bottom') {
        banner.style.left = (screenWidth - banner.style.width) / 2;
        banner.style.top = screenHeight - banner.style.height;
      } else if (style.posType === 'top') {
        banner.style.left = (screenWidth - banner.style.width) / 2;
        banner.style.top = 0;
      } else {
        banner.style.left = style.left;
        banner.style.top = style.top;
      }
      console.log('resizeBanner:', {
        left: banner.style.left,
        top: banner.style.top,
        width: banner.style.width,
        height: banner.style.height,
        posType: style.posType,
        refNode: style.refNode,
      });
    });

    banner.onLoad(() => {
      console.log('banner广告加载成功:' + bannerId);
      if (isPreload) {
        _loadedBanners.push(banner);
        console.log(`成功预载Banner:${bannerId},剩余已预载Banner:${_loadedBanners.length}`);
      }
      if (!isPreload) {
        banner.useTimes++;
        banner.show();
        _currentBanner = banner;
        console.log(`成功载入Banner, 并直接显示:${bannerId},剩余已预载Banner:${_loadedBanners.length}`);
        _preloadBanner();
      }
    });
    banner.onError(err => {
      console.log('banner加载失败:' + bannerId, err);
      if (!isPreload) {
        _currentBanner = null;
      }
    });
    return banner;
  };

  /**
   * bannerId是否已经成功载入
   * @param bannerId
   * @returns {boolean}
   * @private
   */
  let _isBannerIdLoaded = function (bannerId) {
    if (_currentBanner) {
      if (_currentBanner.bannerId === bannerId)
        return false;
    }
    for (let j = 0; j < _loadedBanners.length; j++) {
      let banner = _loadedBanners[j];
      if (banner.bannerId === bannerId) {
        return true;
      }
    }
    return false;
  };

  /**
   * 取一个未被载入的BannerId
   * @returns {*}
   * @private
   */
  let _getNotLoadedBannerId = function () {
    for (let i = 0; i < GAME_BANNER_ID.length; i++) {
      let bannerId = GAME_BANNER_ID[i];
      if (!_isBannerIdLoaded(bannerId)) {
        return bannerId
      }
    }
    return null;
  };


  let _setBannerStyle = function (banner, style) {
    if (banner) {
      banner.resizeToStyle = style;
      banner.style.left = style.left;
      banner.style.top = style.top;
    }
  };


  /**
   * 预载一个banner
   * @private
   */
  let _preloadBanner = function () {
    console.log("预载Banner");
    let bannerId = _getNotLoadedBannerId();
    if (bannerId) {
      _createGameBanner(bannerId, true);
    } else {
      console.log("所有BannerID都被预载, 无需再次预载");
    }
  };

  /**
   * 按指定style显示banner
   * @param style
   * @returns {*}
   * @private
   */
  let _showBannerWithStyle = function (style) {
    let banner = _currentBanner;
    if (!banner) {
      if (_loadedBanners.length > 0) {
        banner = _loadedBanners[0];
        _loadedBanners.splice(0, 1);
        console.log("从已预载Banner中取出一个, 剩余已预载Banner:" + _loadedBanners.length);
        banner.useTimes++;
        banner.show();
        _currentBanner = banner;
        //由于从已载入的Banner中取出了一个, 需要再次预载一个banner供后续使用
        _preloadBanner();
      } else {
        console.log("没有找到已预载Banner, 实时创建一个");
        let bannerId = _getNotLoadedBannerId();
        if (bannerId) {
          banner = _createGameBanner(bannerId, false);
        }
      }
    } else {
      banner.useTimes++;
      banner.show();
    }
    if (banner) {
      _setBannerStyle(banner, style);
    }
    return banner;
  };
  let _hideOrDestroyCurrentBanner = function () {
    if (_currentBanner) {
      _currentBanner.hide();
      if (_currentBanner.useTimes >= Global.SwitchSettings.getBannerReuseTimes()) {
        _currentBanner.destroy();
        _currentBanner = null;
        console.log("销毁Banner");
      }
    }
  };


  let getBannerStyle = function (opts) {
    if (opts === undefined) {
      opts = {
        posType: 'bottom'
      };
    }
    //容错: 如果posType为node, 但refNode没有设置, 改为屏幕底部显示
    if (opts.posType === 'node' && !opts.refNode) {
      console.warn('Banner位置设选项异常, 改为底部显示Banner', opts);
      opts = {
        posType: 'bottom'
      };
    }

    if (_lastBannerOpts &&
      _lastBannerOpts.posType === opts.posType &&
      _lastBannerOpts.refNode === opts.refNode) {
      return Object.assign({}, _lastBannerOpts);
    }

    let sysInfo = wx.getSystemInfoSync();
    let {screenWidth} = sysInfo;
    let result;
    if (opts.posType === 'top') {
      result = {
        top: 0,
        left: 0,
        posType: opts.posType,
      }
    } else if (opts.posType === 'bottom') {
      result = {
        top: 0,
        left: 0,
        posType: opts.posType,
      }
    } else {
      //参考node的boundingBox来显示Banner
      let ratio = cc.view.getDevicePixelRatio();
      let scaleX = cc.view.getScaleX() / ratio;
      let scaleY = cc.view.getScaleY() / ratio;
      let boundingBox = opts.refNode.getBoundingBoxToWorld();

      // 转换为pt坐标
      let width = boundingBox.width * scaleX;
      let height = boundingBox.height * scaleY;
      let left = boundingBox.x * scaleX;
      let top = cc.view.getFrameSize().height - (boundingBox.y * scaleY) - height; // 转换坐标系（左上角原点)
      if (width < 343) {
        console.warn('Banner参考节点宽度小于343, 自动扩充为343');
        let diff = 343 - width;
        width = 343;
        left -= diff / 2;
      }
      result = {
        left,
        top,
        posType: opts.posType,
        refNode: opts.refNode,
      }
    }
    _lastBannerOpts = result;
    return result;
  };


  /**
   * 显示Banner广告, banner显示时的以bannerRefNode作为参考节点,
   * 会确保不超出参考节点的范围, 如果bannerRefNode为空,
   * 则显示在屏幕底部并缩放占满屏幕
   * @param opts
   * @returns {*}
   */
  let showGameBanner = function (opts) {
    //新手引导时, 不显示banner广告
    if (TutorialManager.instance && TutorialManager.instance.tutorialsRunning())
      return null;
    _hideOrDestroyCurrentBanner();

    let style = getBannerStyle(opts);
    let banner = _showBannerWithStyle(style);
    _bannerStyleStack.push(style);
    return banner;
  };

  /**
   * 隐藏banner, 如果堆栈里有其他banner,则恢复前一个样式
   * @param clearStack
   */
  let hideGameBanner = function (clearStack) {
    if (clearStack) {
      _bannerStyleStack = [];
    }
    _hideOrDestroyCurrentBanner();
    if (_bannerStyleStack.length > 0) {
      _bannerStyleStack.splice(_bannerStyleStack.length - 1, 1);
    }
    if (_bannerStyleStack.length === 0 || clearStack) {
      _lastBannerOpts = undefined;
    } else {
      console.log("Banner堆非空, 恢复上一级样式");
      let style = _bannerStyleStack[_bannerStyleStack.length - 1];
      _currentBanner = null;
      _showBannerWithStyle(style);
    }
  };


  /**
   * 设置当前正在显示的Banner的样式
   * @param opts
   */
  let setCurrentGameBannerStyle = function (opts) {
    let style = getBannerStyle(opts);
    _showBannerWithStyle(style);
  };


  let showCurrentGameBanner = function () {
    if (_currentBanner) {
      _currentBanner.show();
    }
  };

  let hideCurrentGameBanner = function () {
    if (_currentBanner) {
      _currentBanner.hide();
    }
  };

  module.exports = {
    initGameBanner,
    showGameBanner,
    hideGameBanner,
    setCurrentGameBannerStyle,
    showCurrentGameBanner,
    hideCurrentGameBanner
  };
}